package com.example.lib.controller;

import com.example.lib.model.Book;
import com.example.lib.model.User;
import com.example.lib.service.BookService;
import com.example.lib.service.UserService;
import com.example.lib.service.impl.UserServiceImpl;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.List;

@Controller
@RequestMapping("user")
public class UserController extends BaseController {
    private final UserService userService;

    public UserController(UserService userService, BookService bookService) {
        this.userService = userService;
        this.bookService = bookService;
    }

    private final BookService bookService;




    @PostMapping(value = "signUp")
    private String signUp(User user) {
        if (userService.queryOne("queryUserByUsername", user) != null) {
            request.setAttribute("error", "用户名已经存在");
        } else {
            return "/sign_up.jsp";
        }
        userService.create(user);
        request.setAttribute("message", "您的ID是：" + user.getId());
        return "redirect:/index.jsp";
    }

    @PostMapping(value = "signIn")
    private String signIn(User user) {
        user = userService.queryOne("queryUserByUsernameAndPassword", user);
        if (user == null) {
            request.setAttribute("error", "用户名或密码错误");
            return "/index.jsp";
        }
        session.setAttribute("user", user);

        List<Book> books = bookService.queryAll();
        request.setAttribute("book",books);
        return "redirect:/user/index.jsp";
    }
    @RequestMapping(value = "signOut", method = RequestMethod.GET)
    private String signOut() {
        session.invalidate();
        return "redirect:/index.jsp";
    }

}
